import { registerPainter } from 'zrender'
import './style.css'
import { GUI } from 'lil-gui'
import CanvasPainter from 'zrender/lib/canvas/Painter'

registerPainter('canvas', CanvasPainter)

const demos = import.meta.glob('./demo/**/*.ts')
const folders = new Map<string, GUI>()

const gui = new GUI({
  title: '菜单'
})

for (const key in demos) {
  const [, group, name] = (/.\/demo\/([^\/]+)\/([^\/]+)\.ts/.exec(key) as unknown) as [unknown, string, string]
  let folder = folders.get(group)
  if (!folder) {
    folder = gui.addFolder(group)
    folders.set(group, folder)
  }
  const menu: {
    [key: string]: () => void
  } = {}
  const path = `${group}/${name}`
  menu[name] = () => {
    location.href = './#/' + path
  }
  folder.add(menu, name)
}

let onLeave: (() => void) | undefined
let menu = gui.addFolder('菜单')

const dom = document.getElementById('app')!
function locate(): void {
  onLeave?.()
  menu.destroy()
  dom.innerHTML = ''
  const hash = decodeURI(location.hash)
  menu = gui.addFolder(hash.replace('#/', ''))
  const key = hash.replace('#', './demo') + '.ts'
  const demo = demos[key]
  if (demo) {
    demo().then(async (e: any) => {
      onLeave = await e.main(dom, menu)
    })
  }
}
window.onhashchange = locate
locate()